<template>
  <div>
    <van-nav-bar title="黑马头条 - 登录" />
    <van-form @submit="onSubmit">
      <van-field v-model="user.mobile" type="tel" label="手机号" placeholder="请输入手机号" required :rules="[{ required: true, message: '请填写手机号', trigger: 'onChange', pattern: /^1[3456789]\d{9}$/  }]" />
      <van-field v-model="user.code" type="password" label="密码" placeholder="请输入密码" required :rules="[{ required: true, message: '输入6位的密码', trigger: 'onChange', pattern: /^\d{6}$/ }]" />
      <div style="margin: 16px;">
        <van-button :disabled="isLoading" :loading="isLoading" loading-text="程序员拼命加载ing..." block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api/index.js'
import { Notify } from 'vant'
import { setToken } from '@/utils/token.js'

export default {
  name: 'Login',
  data () {
    return {
      user: {
        mobile: '13888888888',
        code: '246810' // 默认只能用246810后台规定了
      },
      isLoading: false
    }
  },
  methods: {
    async onSubmit () {
      this.isLoading = true
      try {
        const { data: res } = await loginAPI(this.user)
        // console.log(res.data)
        Notify({ type: 'success', message: '登录成功' })
        // console.log(res.data.token)
        setToken(res.data.token)
        localStorage.setItem('refresh_token', res.data.refresh_token)

        this.$router.replace({
          path: this.$route.query.path || '/layout/home'
        })
      } catch (error) {
        Notify({ type: 'danger', message: '登录失败' })
        console.log(error)
      }
      this.isLoading = false
    }
  }
}
</script>
